package com.demo.java.utils;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.text.MessageFormat;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadUtils {

    public static void sleep(long time, TimeUnit timeUnit) {
        try {
            timeUnit.sleep(time);
        } catch (Exception ex) {
            log.error("sleep error.", ex);
        }
    }

    public static void sleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (Exception ex) {
            log.error("sleep error.", ex);
        }
    }

    public static String threadName() {
        return Thread.currentThread().getName();
    }

    public static ThreadFactory createThreadFactory(String threadName) {
        return new ThreadFactory() {
            @Override
            public Thread newThread(@NotNull Runnable r) {
                return new Thread(r, threadName);
            }
        };
    }

    /**
     * 打印线程调用栈信息
     */
    public static void printStack() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for(StackTraceElement stackTraceElement : stackTrace) {
            if (i++ > 0) {
                sb.append(System.getProperty("line.separator")).append("  -> ");
            }
            sb.append(MessageFormat.format("{0}.{1}() {2}"
                    ,stackTraceElement.getClassName()
                    ,stackTraceElement.getMethodName()
                    ,stackTraceElement.getLineNumber()));
        }
        log.info("====== update to error, invoke stack: " + sb.toString());
    }
}
